package io.github.kuafucv.zero.log.helper.runtime;

import javax.management.*;
import java.util.ArrayList;
import java.util.Set;

public class RuntimeHelper {

    public static int getServerPort(){
        int port = 0 ;
        MBeanServer mBeanServer = null;
        ArrayList<MBeanServer> mBeanServers = MBeanServerFactory.findMBeanServer(null);
        if (!mBeanServers.isEmpty()) {
            mBeanServer = mBeanServers.get(0);
        }
        if (mBeanServer == null) {
            throw new IllegalStateException("没有发现JVM中关联的MBeanServer.");
        }

        Set<ObjectName> objectNames = null;
        try {
            objectNames = mBeanServer.queryNames(new ObjectName("Catalina:type=Connector,*"), null);
        }
        catch (MalformedObjectNameException | NullPointerException ignored) {}

        if (objectNames == null || objectNames.isEmpty()) {
            throw new IllegalStateException("没有发现JVM中关联的MBeanServer : "+ mBeanServer.getDefaultDomain() + " 中的对象名称.");
        }

        try {
            for (ObjectName objectName : objectNames) {
                String protocol = (String) mBeanServer.getAttribute(objectName, "protocol");
                if (protocol.equals("HTTP/1.1")) {
                    port = (Integer) mBeanServer.getAttribute(objectName, "port");
                }
            }
        } catch (AttributeNotFoundException | InstanceNotFoundException | MBeanException | ReflectionException ignored) {
        }
        return port;
    }
}
